<template>
  <div class="menu-container">
    <el-row :gutter="20">
      <!-- 左侧分类栏 -->
      <el-col :span="4">
        <el-card class="category-card">
          <template #header>
            <div class="card-header">
              <span>菜品分类</span>
            </div>
          </template>
          <el-menu
            :default-active="activeCategory"
            @select="handleCategorySelect"
          >
            <el-menu-item v-for="category in categories" :key="category" :index="category">
              {{ category }}
            </el-menu-item>
          </el-menu>
        </el-card>
      </el-col>

      <!-- 右侧菜品列表 -->
      <el-col :span="20">
        <el-row :gutter="20">
          <el-col :span="24" style="margin-bottom: 20px">
            <el-input
              v-model="searchQuery"
              placeholder="搜索菜品"
              prefix-icon="Search"
              clearable
              @clear="loadDishes"
              @input="handleSearch"
            />
          </el-col>
          
          <el-col 
            v-for="dish in dishes" 
            :key="dish.ID" 
            :span="6"
            style="margin-bottom: 20px"
          >
            <el-card 
              class="dish-card" 
              :body-style="{ padding: '0' }"
              @click="showDishDetail(dish)"
            >
              <div class="dish-image-container">
                <el-image
                  :src="dish.image_url || '/default-dish.jpg'"
                  class="dish-image"
                  fit="cover"
                />
              </div>
              <div class="dish-info">
                <h3 class="dish-name">{{ dish.name }}</h3>
                <div class="dish-tags">
                  <el-tag 
                    v-for="tag in parseTags(dish.tags)" 
                    :key="tag" 
                    size="small" 
                    :type="getTagType(tag)"
                    class="dish-tag"
                  >
                    {{ getTagText(tag) }}
                  </el-tag>
                </div>
                <div class="dish-description">{{ dish.description }}</div>
                <div class="dish-footer">
                  <span class="dish-price">¥{{ dish.price }}</span>
                  <el-button 
                    type="primary" 
                    size="small" 
                    @click="addToCart(dish)"
                    :disabled="dish.Stock <= 0"
                  >
                    {{ dish.Stock > 0 ? '加入购物车' : '已售罄' }}
                  </el-button>
                </div>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </el-col>
    </el-row>

    <!-- 添加购物车悬浮按钮 -->
    <div class="cart-fab">
      <el-badge :value="cartItemCount" :hidden="cartItemCount === 0">
        <el-button 
          type="primary" 
          size="large" 
          circle
          @click="cartDrawer = true"
        >
          <el-icon><ShoppingCart /></el-icon>
        </el-button>
      </el-badge>
    </div>

    <!-- 购物车抽屉 -->
    <el-drawer
      v-model="cartDrawer"
      title="购物车"
      direction="rtl"
      size="400px"
    >
      <div class="cart-content">
        <el-empty v-if="!cartItems.length" description="购物车是空的" />
        <template v-else>
          <div class="cart-items">
            <div v-for="item in cartItems" :key="item.ID" class="cart-item">
              <el-checkbox 
                v-model="item.Selected"
                @change="updateCartItemSelection(item)"
              />
              <img 
                :src="item.Dish.image_url || '/default-dish.jpg'" 
                class="cart-item-image"
              />
              <div class="cart-item-info">
                <h4>{{ item.Dish.name }}</h4>
                <div class="cart-item-price">¥{{ item.Price }}</div>
              </div>
              <div class="cart-item-actions">
                <el-input-number 
                  v-model="item.Quantity" 
                  :min="0" 
                  :max="item.Dish.Stock"
                  size="small"
                  @change="(val) => updateCartItem(item, val)"
                />
                <el-button 
                  type="danger" 
                  size="small"
                  circle
                  @click="removeFromCart(item)"
                >
                  <el-icon><Delete /></el-icon>
                </el-button>
              </div>
            </div>
          </div>

          <div class="cart-footer">
            <div class="cart-select-all">
              <el-checkbox 
                v-model="allSelected"
                @change="toggleSelectAll"
              >
                全选
              </el-checkbox>
            </div>
            <div class="cart-total">
              <div>
                已选 {{ selectedCount }} 件
                <span class="total-price">合计: ¥{{ selectedTotal }}</span>
              </div>
              <el-button 
                type="primary" 
                :disabled="selectedCount === 0"
                @click="submitOrder"
              >
                提交订单
              </el-button>
            </div>
          </div>
        </template>
      </div>
    </el-drawer>

    <!-- 订单表单对话框 -->
    <el-dialog
      v-model="orderFormVisible"
      title="提交订单"
      width="30%"
      :before-close="handleClose"
    >
      <el-form
        ref="orderFormRef"
        :model="orderForm"
        :rules="orderFormRules"
        label-width="80px"
      >
        <el-form-item label="就餐方式" prop="orderType">
          <el-radio-group v-model="orderForm.orderType">
            <el-radio-button label="dine_in">堂食</el-radio-button>
            <el-radio-button label="takeout">外卖</el-radio-button>
          </el-radio-group>
        </el-form-item>
        
        <!-- 只在外卖时显示地址和电话输入框 -->
        <template v-if="orderForm.orderType === 'takeout'">
          <el-form-item label="配送地址" prop="address">
            <el-input 
              v-model="orderForm.address"
              placeholder="请输入配送地址"
            />
          </el-form-item>
          <el-form-item label="联系电话" prop="phone">
            <el-input 
              v-model="orderForm.phone"
              placeholder="请输入联系电话"
            />
          </el-form-item>
        </template>
      </el-form>
      <template #footer>
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="confirmOrder">确认</el-button>
      </template>
    </el-dialog>

    <!-- 添加菜品详情弹窗 -->
    <DishDetail
      v-model="dishDetailVisible"
      :dish="selectedDish"
      @add-to-cart="addToCart"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useStore } from 'vuex'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ShoppingCart, Delete } from '@element-plus/icons-vue'
import type { Dish } from '../types'
import DishDetail from '../components/DishDetail.vue'

interface CartItem {
  ID: number
  DishID: number
  Quantity: number
  Price: number
  Selected: boolean
  Dish: Dish
}

const store = useStore()
const router = useRouter()
const activeCategory = ref('')
const searchQuery = ref('')
const dishes = ref<Dish[]>([])
const categories = ref<string[]>([])
const cartDrawer = ref(false)
const cartItems = ref<CartItem[]>([])
const orderType = ref('dine_in')  // 默认堂食
const address = ref('')  // 外卖地址
const orderFormVisible = ref(false)
const orderForm = ref({
  orderType: 'dine_in',
  address: '',
  phone: ''
})

const orderFormRules = {
  orderType: [{ required: true, message: '请选择就餐方式', trigger: 'change' }],
  address: [{ required: true, message: '请输入配送地址', trigger: 'blur' }],
  phone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^1[0-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ]
}

const orderFormRef = ref()

const dishDetailVisible = ref(false)
const selectedDish = ref(null)

// 计算购物车商品总数
const cartItemCount = computed(() => {
  return cartItems.value.reduce((sum, item) => sum + item.Quantity, 0)
})

// 计算已选商品数量
const selectedCount = computed(() => {
  return cartItems.value.filter(item => item.Selected).length
})

// 计算已选商品总价
const selectedTotal = computed(() => {
  return cartItems.value
    .filter(item => item.Selected)
    .reduce((sum, item) => sum + item.Price * item.Quantity, 0)
    .toFixed(2)
})

// 全选状态
const allSelected = computed({
  get: () => cartItems.value.length > 0 && cartItems.value.every(item => item.Selected),
  set: (val) => {
    cartItems.value.forEach(item => {
      item.Selected = val
      updateCartItemSelection(item)
    })
  }
})

// 加载菜品列表
const loadDishes = async () => {
  try {
    let url = 'http://localhost:8080/api/dishes'
    if (activeCategory.value && activeCategory.value !== '全部') {
      url += `?category=${encodeURIComponent(activeCategory.value)}`
    }
    if (searchQuery.value) {
      url += `${url.includes('?') ? '&' : '?'}search=${encodeURIComponent(searchQuery.value)}`
    }

    const response = await fetch(url, {
      headers: {
        'Authorization': `Bearer ${store.state.token}`
      }
    })
    const data = await response.json()
    console.log("data", data)
    if (response.ok) {
      dishes.value = data.dishes.map((dish: any) => ({
        ...dish,
        Tags: dish.Tags ? JSON.parse(dish.Tags) : []
      }))
    }
  } catch (error) {
    console.error('Load dishes error:', error)
    ElMessage.error('加载菜品失败')
  }
}

// 加载分类列表
const loadCategories = async () => {
  try {
    const response = await fetch('http://localhost:8080/api/dishes', {
      headers: {
        'Authorization': `Bearer ${store.state.token}`
      }
    })
    const data = await response.json()
    if (response.ok) {
      // 从所有菜品中提取不重复的分类
      const uniqueCategories = [...new Set(data.dishes.map((dish: any) => dish.Category))]
      categories.value = ['全部', ...uniqueCategories]  // 添加"全部"选项
    }
  } catch (error) {
    console.error('Load categories error:', error)
    ElMessage.error('加载分类失败')
  }
}

// 加载购物车
const loadCart = async () => {
  try {
    const response = await fetch('http://localhost:8080/api/cart', {
      headers: {
        'Authorization': `Bearer ${store.state.token}`
      }
    })
    const data = await response.json()
    if (response.ok) {
      cartItems.value = data.items
    }
  } catch (error) {
    console.error('Load cart error:', error)
    ElMessage.error('加载购物车失败')
  }
}

// 添加到购物车
const addToCart = async (dish: Dish) => {
  try {
    const response = await fetch('http://localhost:8080/api/cart', {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${store.state.token}`,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        dish_id: dish.ID,
        quantity: 1,
        price: dish.price
      })
    })
    if (response.ok) {
      ElMessage.success('已添加到购物车')
      loadCart()  // 重新加载购物车
    }
  } catch (error) {
    console.error('Add to cart error:', error)
    ElMessage.error('添加到购物车失败')
  }
}

// 更新购物车项
const updateCartItem = async (item: CartItem, quantity: number) => {
  try {
    const response = await fetch(`http://localhost:8080/api/cart/${item.ID}`, {
      method: 'PUT',
      headers: {
        'Authorization': `Bearer ${store.state.token}`,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        quantity: quantity,
        selected: item.Selected
      })
    })
    if (response.ok) {
      loadCart()
    }
  } catch (error) {
    console.error('Update cart error:', error)
    ElMessage.error('更新购物车失败')
  }
}

// 删除购物车项
const removeFromCart = async (item: CartItem) => {
  try {
    const response = await fetch(`http://localhost:8080/api/cart/${item.ID}`, {
      method: 'DELETE',
      headers: {
        'Authorization': `Bearer ${store.state.token}`
      }
    })
    if (response.ok) {
      ElMessage.success('已从购物车移除')
      loadCart()
    }
  } catch (error) {
    console.error('Remove from cart error:', error)
    ElMessage.error('删除失败')
  }
}

// 分类筛选
const handleCategorySelect = (category: string) => {
  activeCategory.value = category
  loadDishes()
}

// 搜索
const handleSearch = () => {
  loadDishes()
}

// 更新购物车项选中状态
const updateCartItemSelection = async (item) => {
  try {
    const response = await fetch(`http://localhost:8080/api/cart/${item.ID}`, {
      method: 'PUT',
      headers: {
        'Authorization': `Bearer ${store.state.token}`,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        quantity: item.Quantity,
        selected: item.Selected
      })
    })
    if (!response.ok) {
      throw new Error('更新失败')
    }
  } catch (error) {
    ElMessage.error('更新失败')
  }
}

// 全选/取消全选
const toggleSelectAll = (val) => {
  cartItems.value.forEach(item => {
    item.Selected = val
    updateCartItemSelection(item)
  })
}

// 提交订单
const submitOrder = async () => {
  const selectedItems = cartItems.value.filter(item => item.Selected)
  if (selectedItems.length === 0) {
    ElMessage.warning('请选择要购买的商品')
    return
  }

  // 重置表单
  orderForm.value = {
    orderType: 'dine_in',
    address: '',
    phone: ''
  }
  orderFormVisible.value = true
}

// 确认下单
const confirmOrder = async () => {
  if (!orderFormRef.value) return
  
  // 获取选中的商品
  const selectedItems = cartItems.value.filter(item => item.Selected)
  if (selectedItems.length === 0) {
    ElMessage.warning('请选择要购买的商品')
    return
  }
  
  await orderFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      try {
        const response = await fetch('http://localhost:8080/api/orders', {
          method: 'POST',
          headers: {
            'Authorization': `Bearer ${store.state.token}`,
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({
            order_type: orderForm.value.orderType,
            address: orderForm.value.orderType === 'takeout' ? orderForm.value.address : '',
            phone: orderForm.value.orderType === 'takeout' ? orderForm.value.phone : '',
            items: selectedItems.map(item => ({
              dish_id: item.DishID,
              quantity: item.Quantity,
              price: item.Price
            }))
          })
        })

        if (response.ok) {
          const data = await response.json()
          ElMessage.success('下单成功')
          orderFormVisible.value = false
          cartDrawer.value = false
          
          // 清空已选商品
          const selectedIds = selectedItems.map(item => item.ID)
          await fetch('http://localhost:8080/api/cart', {
            method: 'DELETE',
            headers: {
              'Authorization': `Bearer ${store.state.token}`,
              'Content-Type': 'application/json'
            },
            body: JSON.stringify({
              item_ids: selectedIds
            })
          })
          // 重新加载购物车
          loadCart()
        } else {
          const error = await response.json()
          throw new Error(error.error || '下单失败')
        }
      } catch (error) {
        ElMessage.error(error.message || '下单失败')
      }
    }
  })
}

// 关闭对话框
const handleClose = () => {
  orderFormVisible.value = false
}

// 添加一个解析标签的函数
const parseTags = (tags: string | string[]) => {
  if (typeof tags === 'string') {
    try {
      return JSON.parse(tags);
    } catch {
      return [];
    }
  }
  return tags || [];
}

// 根据标签内容返回不同的类型
const getTagType = (tag: string) => {
  const tagTypeMap: Record<string, string> = {
    '辣': 'danger',
    '特辣': 'danger',
    '中辣': 'warning',
    '微辣': 'warning',
    '酸': 'warning',
    '甜': 'success',
    '咸': 'info',
    '招牌': 'primary',
    '新品': ''
  }
  return tagTypeMap[tag] || ''
}

// 添加标签文本处理函数
const getTagText = (tag: string) => {
  return tag.trim()
}

const showDishDetail = (dish: any) => {
  selectedDish.value = dish
  dishDetailVisible.value = true
}

onMounted(() => {
  loadCategories()
  loadDishes()
  loadCart()
})
</script>

<style scoped>
.menu-container {
  padding: 20px;
}

.category-card {
  position: sticky;
  top: 20px;
}

.dish-card {
  height: 100%;
  display: flex;
  flex-direction: column;
  transition: all 0.3s;
}

.dish-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.12);
}

.dish-image-container {
  position: relative;
  width: 100%;
  padding-top: 75%; /* 4:3 的图片比例 */
  overflow: hidden;
}

.dish-image {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.dish-info {
  padding: 14px;
  flex: 1;
  display: flex;
  flex-direction: column;
  background: white;
}

.dish-name {
  margin: 0;
  font-size: 16px;
  font-weight: 500;
  color: #333;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.dish-tags {
  margin: 8px 0;
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
}

.dish-tag {
  margin: 0 !important;
}

.dish-description {
  font-size: 13px;
  color: #666;
  margin: 8px 0;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  min-height: 36px;
}

.dish-footer {
  margin-top: auto;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.dish-price {
  color: #f56c6c;
  font-size: 18px;
  font-weight: bold;
}

.cart-fab {
  position: fixed;
  right: 40px;
  bottom: 40px;
  z-index: 1000;
}

.cart-content {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.cart-items {
  flex: 1;
  overflow-y: auto;
  padding: 0 20px;
}

.cart-item {
  display: flex;
  align-items: center;
  padding: 10px 0;
  border-bottom: 1px solid #eee;
}

.cart-item-image {
  width: 60px;
  height: 60px;
  object-fit: cover;
  margin: 0 10px;
  border-radius: 4px;
}

.cart-item-info {
  flex: 1;
  margin-right: 10px;
}

.cart-item-info h4 {
  margin: 0;
  font-size: 14px;
}

.cart-item-price {
  color: #f56c6c;
  font-size: 14px;
  margin-top: 4px;
}

.cart-item-actions {
  display: flex;
  align-items: center;
  gap: 10px;
}

.cart-footer {
  border-top: 1px solid #eee;
  padding: 20px;
  background: #fff;
}

.cart-select-all {
  margin-bottom: 10px;
}

.cart-total {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.total-price {
  color: #f56c6c;
  font-size: 18px;
  font-weight: bold;
  margin-left: 10px;
}

/* 响应式布局 */
@media screen and (max-width: 1400px) {
  .el-col {
    width: 25%;
  }
}

@media screen and (max-width: 1200px) {
  .el-col {
    width: 33.33%;
  }
}

@media screen and (max-width: 768px) {
  .el-col {
    width: 50%;
  }
}

@media screen and (max-width: 480px) {
  .el-col {
    width: 100%;
  }
}
</style> 